package com.lysj.website.auth.controller;

import cn.hutool.crypto.digest.BCrypt;
import com.auth0.jwt.JWT;
import com.auth0.jwt.algorithms.Algorithm;
import com.lysj.website.auth.AuthConstant;
import com.lysj.website.auth.domain.User;
import com.lysj.website.auth.service.UserService;
import com.lysj.website.common.constant.CommonConstant;
import com.lysj.website.common.spring.base.BaseContent;
import com.lysj.website.common.web.ParamUtil;
import com.lysj.website.common.web.Resp;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * @author Created by zk on 2019-01-02 17:53
 * @description
 */
@RestController
@RequestMapping("/auth/admin")
@Slf4j
public class ManagementController extends BaseContent {
    @Resource
    private UserService userService;


    @Value("${secret.tokenExpiration}")
    private int tokenExpiration;

    @PostMapping("/login")
    public Resp login(String username, String password) {
        User user = userService.getRepository().findByUsernameAndDelFlag(username, CommonConstant.NORMAL_FLAG);
        if (ParamUtil.isBlank(user)) {
            return new Resp().error(Resp.Status.PARAM_ERROR, "用户名不存在");
        }
        if (user.getStatus().equals(User.Status.DISABLE.getCode())) {
            return new Resp().error(Resp.Status.PARAM_ERROR, "用户已被禁用");
        }
        if (!BCrypt.checkpw(password, user.getPassword())) {
            return new Resp().error(Resp.Status.PARAM_ERROR, "密码错误");
        }
        String key = user.getUsername();
        String token = JWT.create().withIssuer(AuthConstant.AUTH_NAME).withSubject(user.getId())
                .withExpiresAt(new Date(new Date().getTime() + tokenExpiration * 60 * 1000))
                .sign(Algorithm.HMAC512(key));
        Map<String, Object> map = new HashMap<>();
        map.put("token", token);
        map.put("username", username);
        map.put("name", user.getName());
        return new Resp().success(map, "登录成功");
    }

}
